OssClient = function(editorUi, authName)
{
    var _this = this;
    init(function(ossConfig){
        DrawioClient.call(_this, editorUi, ossConfig.sessionId);
        _this.authUri = ossConfig.authUri;
        _this.saveUri = ossConfig.saveUri;
        _this.openUri = ossConfig.openUri;
        _this.pickUri = ossConfig.pickUri;
    });
};

mxUtils.extend(OssClient, DrawioClient);

OssClient.prototype.authUri = null;

OssClient.prototype.saveUri = null;

OssClient.prototype.openUri = null;

OssClient.prototype.pickUri = null;

OssClient.prototype.token = null;

OssClient.prototype.tokenName = 'key';

OssClient.prototype.extension = '.kdw';


OssClient.prototype.getCookie = function(cookieName){
    var strCookie = document.cookie;
    var arrCookie = strCookie.split("; ");
    for(var i = 0; i < arrCookie.length; i++){
        var arr = arrCookie[i].split("=");
        if(cookieName == arr[0]){
            return arr[1];
        }
    }
    return null;
}


OssClient.prototype.getPersistentToken = function(){
    var token = this.getCookie(this.cookieName);
    return token;
}

OssClient.prototype.clearPersistentToken = function(){
    var expiration = new Date();
    expiration.setYear(expiration.getFullYear() - 1);
    document.cookie = this.cookieName + '=; expires=' + expiration.toUTCString();
}

/**
 * Authorizes the client, gets the userId and calls <open>.
 */
OssClient.prototype.setPersistentToken = function(token, sessionOnly)
{
    try
    {
        if (token != null)
        {
            var expiration = new Date();
            expiration.setYear(expiration.getFullYear() + 10);
            var cookie = this.cookieName + '=' + token + '; path=/' + (sessionOnly? '' : '; expires=' + expiration.toUTCString());

            if (document.location.protocol.toLowerCase() == 'https')
            {
                cookie = cookie + ';secure';
            }

            document.cookie = cookie;
        }
        else
        {
            this.clearPersistentToken();
        }
    }
    catch (e)
    {
        this.ui.handleError(e);
    }
};

OssClient.prototype.emptyFn = function(){};

OssClient.prototype.sendRequest = function(url, params, method, success, error){
    try{
        var req = new mxXmlRequest(url, params, method, false);
        //携带cookie
        req.withCredentials = true;
        req.setRequestHeaders = function(request)
        {
            request.setRequestHeader('Content-Type', 'application/json');
        };
        req.send(function(req){
            var resultData = JSON.parse(req.request.response);
            success(resultData);
        });
    } catch (e){
        if(error){
            error(e);
            this.token = null;
            this.clearPersistentToken();
        }
    }

}

OssClient.prototype.checkToken = function(fn)
{
    if (this.token == null)
    {
        this.authenticate(fn, this.emptyFn);
    }
    else
    {
        fn();
    }
};

OssClient.prototype.authenticate = function(success, error, failOnAuth)
{
    if (window.onOssCallback == null)
    {
        var auth = mxUtils.bind(this, function()
        {
            var acceptAuthResponse = true;
            var authToken = this.getPersistentToken();
            if (authToken != null)
            {
                success();
            }
            else
            {
                this.ui.showAuthDialog(this, true, mxUtils.bind(this, function(remember, authSuccess)
                {
                    var url = this.authUri;
                    var width = 1000,
                        height = 730,
                        screenX = window.screenX,
                        screenY = window.screenY,
                        outerWidth = window.outerWidth,
                        outerHeight = window.outerHeight;

                    var left = screenX + Math.max(outerWidth - width, 0) / 2;
                    var top = screenY + Math.max(outerHeight - height, 0) / 2;

                    var features = ['width=' + width, 'height=' + height,
                        'top=' + top, 'left=' + left,
                        'status=no', 'resizable=yes',
                        'toolbar=no', 'menubar=no',
                        'scrollbars=yes'];
                    var popup = window.open(url, 'ossauth', features.join(','));
                    if (popup != null)
                    {
                        window.onOssCallback = mxUtils.bind(this, function(authWindow)
                        {
                            var authToken = this.getPersistentToken();//authInfo;//[this.tokenName]
                            if (acceptAuthResponse)
                            {
                                window.onOssCallback = null;
                                acceptAuthResponse = false;

                                try
                                {
                                    if (authToken == null)
                                    {
                                        error({message: mxResources.get('accessDenied'), retry: auth});
                                    }
                                    else
                                    {
                                        if (authSuccess != null)
                                        {
                                            authSuccess();
                                        }

                                        this.token = authToken;
                                        //this.setPersistentToken(authToken, !remember);
                                        success();
                                    }
                                }
                                catch (e)
                                {
                                    error(e);
                                }
                                finally
                                {
                                    if (authWindow != null)
                                    {
                                        authWindow.close();
                                    }
                                }
                            }
                            else if (authWindow != null)
                            {
                                authWindow.close();
                            }
                        });

                        popup.focus();
                    }
                }), mxUtils.bind(this, function()
                {
                    if (acceptAuthResponse)
                    {
                        window.onOssCallback = null;
                        acceptAuthResponse = false;
                        error({message: mxResources.get('accessDenied'), retry: auth});
                    }
                }));
            }
        });

        auth();
    }
    else
    {
        error({code: App.ERROR_BUSY});
    }
};

OssClient.prototype.pickFile = function(){
    window.open(this.pickUri,'_blank','');
};

OssClient.prototype.logout = function(){
    this.clearPersistentToken();
    this.token = null;
}

var init = function(success){
    try{
        var url = document.location.origin + document.location.pathname + 'OssOpen?initConfig=true';
        var req = new mxXmlRequest(url, null, "GET", false);
        req.send(function(req){
            var resultData = JSON.parse(req.request.response);
            success(resultData);
        });
    } catch (e){
        console.log(e);
    }
}
